package com.service.imp;

import com.common.Base;
import com.common.Result;
import com.entity.Letter;
import com.entity.User;
import com.repository.LetterRepository;
import com.repository.UserRepository;
import com.service.LetterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author：Luohuiyong
 * @Description:
 * @Date: Created in 11:40 2019/2/1
 */
@Service
public class LetterServiceImp implements LetterService {

    @Autowired
    private LetterRepository letterRepository;

    @Autowired
    private UserRepository userRepository;

    @Override
    public Letter findOne(Letter bean) {
        Optional<Letter> letterOptional = letterRepository.findById(bean.getId());
        Letter letter = letterOptional.get();

        return letter;
    }

    /**
     * 写信
     * @param letter
     * @return
     */
    @Override
    public Result create(Letter letter ) {
        if(letter.getAddresseeId() == null){
            //获取userId列表
            List<User> userList = userRepository.findAll();
            List<Integer> idList = new ArrayList();
            for (int i = 0; i < userList.size();i++){
                if(letter.getWriterId() != userList.get(i).getId()){
                    idList.add(userList.get(i).getId());
                }
            }
            //再随机从id列表中抽取收信人id
            Random random = new Random();
            int num = random.nextInt(userList.size() -1);
            int addresseeId = idList.get(num);
            letter.setAddresseeId(addresseeId);
        }
        letter.setCreatedAt(new Date());

        letterRepository.save(letter);
        return Base.success();
    }


    /**
     * 分页获取来信
     * @param letter
     * @return
     */
    @Override
    public Result index(Letter letter) {
        Pageable pageable = new PageRequest(letter.getPage(),letter.getPageSize(), Sort.Direction.DESC,"createdAt");
        Page<Letter> page = letterRepository.findAllByAddresseeId(letter.getAddresseeId(),pageable);
        int total = letterRepository.countByAddresseeId(letter.getAddresseeId());
        int maxPage = total/letter.getPageSize();

        return Base.success(page.getContent(),total,maxPage);
    }

}
